package com.application.sistercityapplication.main;

import java.util.List;

import com.application.sistercityapplication.dto.MagazineDto;
import com.application.sistercityapplication.json.JSONParserForGetList;
import com.application.sistercityapplication.listadapter.DocumentListAdapter;
import com.application.sistercityapplication.model.Magazine;
import com.application.sistercityapplication.utils.SwipeDismissListViewTouchListener;
import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu;
import com.roscopeco.ormdroid.Entity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.Toast;

@SuppressLint("ValidFragment")
public class DocumentPageFragment extends Fragment {
	private ProgressBar pBar;
	private View v,v2;
	private LayoutInflater inflater2;
	private FrameLayout mainLayout;
	private String country_name;
	private ListView docList;
	private int cId;
	private ImageView menuToggle;
	private SlidingMenu sm;
	public DocumentPageFragment(int country_id,String count_name,SlidingMenu sm){
		this.cId = country_id;
		this.country_name = count_name;
		this.sm = sm;
	}
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
		
		v = inflater.inflate(R.layout.new_activity_city_information_main, container,false);

		mainLayout = (FrameLayout) v.findViewById(R.id.frameForInflate);
		inflater2 = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		v2 = inflater2.inflate(R.layout.activity_document_layout, null);
//		ImageView back_icon = (ImageView) v2.findViewById(R.id.back_icon);
//		back_icon.setVisibility(View.INVISIBLE);
		menuToggle = (ImageView) v2.findViewById(R.id.menuToggle);
		menuToggle.setVisibility(View.INVISIBLE);
		pBar = (ProgressBar) v2.findViewById(R.id.progress);
		docList = (ListView) v2.findViewById(R.id.documentListView);
		mainLayout.addView(v2);

		new DownloadDocumentTask(getActivity().getApplicationContext(),getActivity(),pBar).execute();
		menuToggle.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				sm.toggle();
			}
		});
		return v;
	}
	public class DownloadDocumentTask extends AsyncTask<String, Void, List<MagazineDto>>{
		ProgressDialog pDialog;
		private Context context;
		public Activity _activity;
		private ProgressBar _resId;
		private boolean isDismiss = false;
		private Magazine mag;
		public DownloadDocumentTask(Context context,Activity act,ProgressBar resid) {
			super();
			this.context = context;
			this._activity = act;
			this._resId = resid;
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
//			pDialog = new ProgressDialog(MainHomePageViewActivity.this);
//			pDialog.setMessage("Loading Document...");
//			pDialog.show();
			_resId.setVisibility(View.VISIBLE);
		}
		@Override
		protected List<MagazineDto> doInBackground(String... params) {
			// TODO Auto-generated method stub
			JSONParserForGetList json = JSONParserForGetList.getInstance();
			List<MagazineDto> magList = null;
			magList = json.getMagazines(cId+"");
			return magList;
		}
		@Override
		protected void onPostExecute(List<MagazineDto> result) {
			super.onPostExecute(result);
			_resId.setVisibility(View.GONE);
			menuToggle.setVisibility(View.VISIBLE);
			final DocumentListAdapter docAdapter = new DocumentListAdapter(result,getActivity().getApplicationContext(),getActivity());
			
			if (result != null) {
				
				SwipeDismissListViewTouchListener touchListener =
			                new SwipeDismissListViewTouchListener(
			                		docList,
			                        new SwipeDismissListViewTouchListener.DismissCallbacks() {
			                            @Override
			                            public boolean canDismiss(int position) {
			                            	boolean isValid = false;
			                            	MagazineDto dto = (MagazineDto) docList.getItemAtPosition(position);
			                            	mag = Entity.query(Magazine.class).where("magId").eq(dto.getMagId()).execute();
			                    			if(mag!=null){
			                    				isValid = true;
			                    			}else{
			                    				isValid = false;
			                    			}
			                                return isValid;
			                            }

			                            @Override
			                            public void onDismiss(ListView listView, int[] reverseSortedPositions) {
			                            	
			                                for (int position : reverseSortedPositions) {
			                                    //mAdapter.remove(mAdapter.getItem(position));
			                                	//docAdapter.
			                                	View view = docList.getChildAt(position);
			                                	final ImageView deleteBt =  (ImageView) view.findViewById(R.id.deleteBookBtn);
			                                	final ImageView dowloadBt =  (ImageView) view.findViewById(R.id.downLoadBookBtn);
			                                	if(!isDismiss){
			                                	deleteBt.setVisibility(View.VISIBLE);
			                                	isDismiss = true;
			                                	deleteBt.setOnClickListener(new OnClickListener() {
													
													@Override
													public void onClick(View v) {
														mag.delete();
														deleteBt.setVisibility(View.GONE);
														dowloadBt.setVisibility(View.VISIBLE);
														docAdapter.notifyDataSetChanged();
													}
												});
			                                	}else{
			                                	deleteBt.setVisibility(View.GONE);
				                                isDismiss = false;	
			                                	}
			                                }
			                                docAdapter.notifyDataSetChanged();
			                            }
			                        });
				docList.setOnTouchListener(touchListener);
				docList.setAdapter(docAdapter);
			} else {
				(Toast.makeText(context, "An error occured.", Toast.LENGTH_LONG)).show();
			}

		}
		
	}
}
